const UserService = require("../../services/admin/UserService")
const JWT = require("../../utils/JWT")

/*
 * @Description: UserController
 */
const UserController = {
  login: async (req, res) => {
    var result = await UserService.login(req.body)
    if (result?.length === 0) {
      res.send({
        code: -1,
        msg: '用户名/密码不匹配'
      })
    } else {
      // 生成token
      const token = JWT.generate({
        _id: result[0]._id, username: result[0].username
      }, '1d');
      res.header('Authorization', token);
      res.send({
        code: 200,
        msg: '登录成功',
        data: {
          username: result[0].username,
          sex: result[0].sex ? result[0].sex : 0,
          avatar: result[0].avatar,
          role: result[0].role
        }
      })
    }
  },
  upload: async (req, res) => {
    const { username, sex } = req.body
    const token = req.headers['authorization'].split(' ')[1]
    var payload = JWT.verify(token)
    const avatar = req.file ? `/avataruploads/${req.file.filename}` : ''
    await UserService.upload({ _id: payload._id, username, sex: Number(sex), avatar })
    if (avatar) {
      res.send({
        code: 200,
        msg: '上传成功',
        data: {
          username, sex: Number(sex), avatar
        }
      })
    } else {
      res.send({
        code: 200,
        msg: '上传成功',
        data: {
          username, sex: Number(sex)
        }
      })
    }
  },
  add: async (req, res) => {
    const { username, sex, role, password, } = req.body
    const avatar = req.file ? `/avataruploads/${req.file.filename}` : ''
    await UserService.add({ username, sex: Number(sex), avatar, role: Number(role), password })
    res.send({
      code: 200,
      msg: '添加成功',
    })
  },
  getList: async (req, res) => {
    const id = req.params.id
    const result = await UserService.getList(id)
    res.send({
      code: 200,
      data: result,
      msg: '数据获取成功',
    })
  },
  delOne: async (req, res) => {
    const id = req.params.id
    const result = await UserService.delOne({ _id: id })
    res.send({
      code: 200,
      msg: '删除成功',
    })
  },
  updateOne: async (req, res) => {
    const result = await UserService.updateOne(req.body)
    res.send({
      code: 200,
      msg: '更新成功',
    })
  },
}
module.exports = UserController
